﻿using DBMC_Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace DBMC
{
    /// <summary>
    /// SaveSubmission.xaml 的交互逻辑
    /// </summary>
    public partial class SaveSubmission : Window
    {
        private bool isDragging;
        private Point startPoint;
        public string SaveName, SavePath;
        EmailService emailService = new EmailService();

        public SaveSubmission(string SaveName, string SavePath)
        {
            InitializeComponent();
            this.SaveName = SaveName;
            this.SavePath = SavePath;
            Title = $"地图快速投稿 - {SaveName}";
            MapName.Text = SaveName;
            Loaded +=  delegate
            {
                LauncherCore.WriteLog($"启动器核心：地图快速投稿 - 页面正常打开，{SaveName} 存档");
            };
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            isDragging = true;
            startPoint = e.GetPosition(this);
        }

        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                Point currentPoint = e.GetPosition(this);
                this.Left += currentPoint.X - startPoint.X;
                this.Top += currentPoint.Y - startPoint.Y;
            }
        }

        private void Window_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            isDragging = false;
        }

        private void ExitApp_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private async void SendSaveToSubmission_Click(object sender, RoutedEventArgs e)
        {
            LauncherCore.WriteLog($"启动器核心：地图快速投稿 - 用户点击了“确认投稿”");
            if (Decision == null)
            {
                LauncherCore.WriteLog($"启动器核心：地图快速投稿 - 正在打包 {SaveName}/{SavePath} 存档中...");
                Main.Visibility = Visibility.Hidden;
                MainLoading.Visibility = Visibility.Visible;
                MainLoadingTips.Text = "打包中...";
                string filePath = await LauncherTools.CreateZipFromFolderAsync2(SavePath, LauncherTools.SavePath);
                LauncherCore.WriteLog($"启动器核心：地图快速投稿 - 打包 {SaveName}/{SavePath} 存档完成");
                EmailService.MapData mapInfo = new EmailService.MapData
                {
                    MapName = MapName.Text,
                    MapResourcePack = MapResourcePackCheckBox.IsChecked == false ? "无" : MapResourcePack.Text,
                    MapAuthor = MapAuthor.Text,
                    MapIntroduce = MapIntroduce.Text,
                    MapDouyuName = MapDouyuName.Text,
                    MapAuthorTalk = MapAuthorTalk.Text,
                    MapAuthorMail = MapAuthorMail.Text
                };
                LauncherCore.WriteLog($"启动器核心：地图快速投稿 - 正在准备投稿中...");
                MainLoadingTips.Text = "投稿中...";
                await Task.Delay(2000);
                if (File.Exists(filePath))
                {
                    PostMail(MapAuthorMail.Text, mapInfo, filePath, !IsFilePath(MapResourcePack.Text) ? null : MapResourcePack.Text);
                }
                else
                {
                    MainLoading.Visibility = Visibility.Hidden;
                    Status.Visibility = Visibility.Visible;
                    Status_EmailRemoveOutline.Visibility = Visibility.Visible;
                    Status_EmailCheckOutline.Visibility = Visibility.Hidden;
                    StatusTips.Text = "投稿失败 - 未选中地图文件";
                    LauncherCore.WriteLog($"启动器核心：地图快速投稿 -  投稿失败，因为未选中存档");
                }
            }
            else
            {
                MessageBox.Show($"{Decision} 为空或格式错误");
            }
        }

        public async void PostMail(string toAddress, EmailService.MapData mapData, string filePath, string filePath2)
        {
            // 邮件主题
            string subject = "地图投稿";

            try
            {
                await emailService.SubmissionAsync(toAddress, subject, mapData, filePath,  filePath2);
                MainLoading.Visibility = Visibility.Hidden;
                Status.Visibility = Visibility.Visible;
                Status_EmailRemoveOutline.Visibility = Visibility.Hidden;
                Status_EmailCheckOutline.Visibility = Visibility.Visible;
                StatusTips.Text = "投稿成功";
                LauncherCore.WriteLog($"启动器核心：地图快速投稿 - 投稿成功");
                //Console.WriteLine("发送成功");
                await Task.Delay(1000);
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                    Close();
                    LauncherCore.WriteLog($"启动器核心：地图快速投稿 - 已删除缓存文件与关闭页面");
                }
            }
            catch (FileNotFoundException ex)
            {
                MainLoading.Visibility = Visibility.Hidden;
                Status.Visibility = Visibility.Visible;
                Status_EmailRemoveOutline.Visibility = Visibility.Visible;
                Status_EmailCheckOutline.Visibility = Visibility.Hidden;
                StatusTips.Text = "投稿失败 - " + ex.Message;
                LauncherCore.WriteLog($"启动器核心：地图快速投稿 - 投稿失败，因为：{ex.Message}");
                //Console.WriteLine(ex.Message);
                await Task.Delay(1000);
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                    Close();
                    LauncherCore.WriteLog($"启动器核心：地图快速投稿 - 已删除缓存文件与关闭页面");
                }
            }
            catch (InvalidOperationException ex)
            {
                MainLoading.Visibility = Visibility.Hidden;
                Status.Visibility = Visibility.Visible;
                Status_EmailRemoveOutline.Visibility = Visibility.Visible;
                Status_EmailCheckOutline.Visibility = Visibility.Hidden;
                StatusTips.Text = "投稿失败 - " + ex.Message;
                LauncherCore.WriteLog($"启动器核心：地图快速投稿 - 投稿失败，因为：{ex.Message}");
                //Console.WriteLine(ex.Message);
                await Task.Delay(1000);
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                    Close();
                    LauncherCore.WriteLog($"启动器核心：地图快速投稿 - 已删除缓存文件与关闭页面");
                }
            }
            catch (Exception ex)
            {
                MainLoading.Visibility = Visibility.Hidden;
                Status.Visibility = Visibility.Visible;
                Status_EmailRemoveOutline.Visibility = Visibility.Visible;
                Status_EmailCheckOutline.Visibility = Visibility.Hidden;
                StatusTips.Text = "投稿失败 - " + ex.Message;
                LauncherCore.WriteLog($"启动器核心：地图快速投稿 - 投稿失败，因为：{ex.Message}");
                //Console.WriteLine(ex.Message);
                await Task.Delay(1000);
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                    Close();
                    LauncherCore.WriteLog($"启动器核心：地图快速投稿 - 已删除缓存文件与关闭页面");
                }
            }
        }

        private string Decision
        {
            get
            {
                if (string.IsNullOrEmpty(MapName.Text))
                {
                    return "地图名称";
                }
                else if (MapResourcePackCheckBox.IsChecked == true && !(IsUrl(MapResourcePack.Text) || IsFilePath(MapResourcePack.Text)))
                {
                        return "资源包";
                }
                else if (string.IsNullOrWhiteSpace(MapAuthor.Text))
                {
                    return "作者名称";
                }
                else if (string.IsNullOrEmpty(MapIntroduce.Text))
                {
                    return "地图介绍";
                }
                else if (string.IsNullOrWhiteSpace(MapDouyuName.Text))
                {
                    return "斗鱼昵称";
                }
                else if (!IsValidEmail(MapAuthorMail.Text))
                {
                    return "你的邮箱";
                }
                return null;
            }
        }

        private bool IsValidEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                return false;
            }

            try
            {
                // 你提供的电子邮件匹配模式
                string pattern = @"\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}";

                // 使用正则表达式匹配输入的电子邮件
                Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
                return regex.IsMatch(email);
            }
            catch (RegexMatchTimeoutException)
            {
                return false;
            }
        }

        private bool IsFilePath(string input)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return false;
            }
            return File.Exists(input) || Directory.Exists(input);
        }

        private bool IsUrl(string input)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                return false;
            }
            string pattern = @"^((https|http)?:\/\/)[^\s]+";
            return Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase);
        }
    }
}